package com.easylinkin.linkappapi.lobar.util;
 
import cn.hutool.core.util.ZipUtil;
import com.easylinkin.bases.aliyun.AliyunSmsUtils;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import org.slf4j.Logger;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
 
/**
 * 解析文件工具类
 *
 * @since 2022/7/12
 */
@SuppressWarnings("unused")
public class UnZipUtils {

    private static final Logger LOGGER = org.slf4j.LoggerFactory
        .getLogger(UnZipUtils.class);
 
    public static int BYTE_LEN = 10240;
 
    /**
     * 本地文件解压
     *
     * @param file 具体文件
     * @return 解压后的文件列表
     */
    public static List<UnzipFileVo> unzip(File file) throws IOException {
//        ZipUtil.unzip(file.getPath(), file.getPath());
        if (Objects.isNull(file) || !file.exists()) {
            return Collections.emptyList();
        }
        ZipFile zip = null;
        try {
            zip = new ZipFile(file);
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        if (Objects.isNull(zip)) {
            return Collections.emptyList();
        }
        Enumeration<? extends ZipEntry> entries = zip.entries();
        List<UnzipFileVo> vos = new ArrayList<>();
        try {
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();

                String path = entry.getName();
                UnzipFileVo vo = new UnzipFileVo();
                InputStream inputStream = zip.getInputStream(entry);
                vo.setInputStream(inputStream);
                vo.setPath(path);
                long size = entry.getSize();
                vo.setSize(size);
                vo.setName(path.substring(0,path.lastIndexOf(".")));
                // 解析文件夹
                boolean directory = entry.isDirectory();
                if (directory) {
                    vo.setType(0);
                    vos.add(vo);
                    continue;
                }
                // 解析文件
                vo.setType(1);
    //            StringBuilder sb = new StringBuilder();
    //            try (InputStream in = inputStream;
    //                 InputStreamReader inputStreamReader = new InputStreamReader(in);
    //                 BufferedReader reader = new BufferedReader(inputStreamReader)) {
    //                String line;
    //                while ((line = reader.readLine()) != null) {
    //                    sb.append(line).append("\n");
    //                }
    //            } catch (IOException e) {
    //                e.printStackTrace();
    //            }
    //            vo.setContent(sb.toString());
                vos.add(vo);
            }
        } catch (Exception e) {
            throw new BusinessException("压缩包内文件格式错误");
        }
//        if (Objects.nonNull(zip)) {
//            try {
//                zip.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        return vos;
    }

    public static void main(String[] args) {

    }

    /**
     * 上传文件解压
     *
     * @param multipartFile 上传文件
     * @return 解压后的文件列表
     */
    public static List<UnzipFileVo> unzip(MultipartFile multipartFile, String dir)
        throws IOException {

        //刪除一個月之前的臨時文件
        File file = getFile(multipartFile,dir);
        if (Objects.isNull(file)) {
            return Collections.emptyList();
        }
        List<UnzipFileVo> vos = unzip(file);
        return vos;
    }
 
    /**
     * MultipartFile 转 File
     *
     * @param multipartFile 上传文件
     * @return 本地文件
     */
    private static File getFile(MultipartFile multipartFile,String dir) {
        //不存在就創建
        fileDirectoryExists(dir);
        //刪除超期的臨時文件
        clearFilesByDay(dir);
        String fileName = System.currentTimeMillis() + "_" + multipartFile.getOriginalFilename();
        File file = new File(dir + fileName);
        int len;
        try (OutputStream os = new FileOutputStream(file);
             InputStream in = multipartFile.getInputStream()) {
            byte[] buffer = new byte[BYTE_LEN];
            while ((len = in.read(buffer, 0, BYTE_LEN)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (IOException e) {
            LOGGER.info("复制报错:{1}",e);
            e.printStackTrace();
            throw new BusinessException("复制文件流时失败:"+e.getMessage());
//            e.printStackTrace();
//            return null;
        }
        return file;
    }

    public static void fileDirectoryExists(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public static void clearFilesByDay(String path) {
        File scFileDir = new File(path);
        File[] TrxFiles = scFileDir.listFiles();
        File[] var3 = TrxFiles;
        int var4 = TrxFiles.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            File curFile = var3[var5];
            Date date = new Date(curFile.lastModified());
            long fileTime = date.getTime();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(5, -3);
            long comparedTime = calendar.getTimeInMillis();
            if (fileTime < comparedTime) {
                curFile.delete();
            }
        }
    }
}